#include<func.h>
#include"head.h"

int rm(char *argv,char *pwd,int netFd){
    //remove /lsy/file
    //pwd /usr1
    char arr[100] = "";
    strcpy(arr, argv);
    char *word = strtok(arr," ");
    char *filePath = strtok(NULL," ");
    char realPath[200] = {0};
    sprintf(realPath, ".%s", filePath);
    printf("realPath = %s\n", realPath);
    int ret = remove(realPath);
    ERROR_CHECK(ret, -1, "remove");
    if(ret == -1){
        send(netFd, "2", 1, MSG_NOSIGNAL);
    }else{
        send(netFd, "1", 1, MSG_NOSIGNAL);
    }
}

/*cd还需优化功能：
    1. cd ..
    2. 禁止用户cd到其他用户目录下*/
int cd(char *argv,char *pwd,int netFd){
    // cd /xxx/xxx/xxx
    //cd /usr1/dir1
    //pwd /usr1
    char arr[100] = "";
    strcpy(arr, argv);
    char *word = strtok(arr," ");
    char *filePath = strtok(NULL," ");
    //判断是否有此路径
    char realPath[200] = {0};
    sprintf(realPath, ".%s", filePath);
    printf("realPath = %s\n", realPath);
    if(access(realPath, 0) == -1){
        send(netFd, "0", 1, MSG_NOSIGNAL);
    }else{
        send(netFd, "1", 1, MSG_NOSIGNAL);
        strcpy(pwd, filePath); 
    }
    printf("%s\n", pwd);
}

int ls(char *pwd, int netFd){
    char filePath[100] = {0};
    sprintf(filePath, "%s%s", ".", pwd); //./usr1/xxx/xxxx
    DIR* pdir = opendir(filePath); //打开目录流
    ERROR_CHECK(pdir, NULL, "opendir");
    struct dirent* pdirent;
    char buf[1000] = {0};
    while((pdirent = readdir(pdir)) != NULL){ //遍历目录流
        if(strcmp(pdirent->d_name, ".") == 0 || strcmp(pdirent->d_name, "..") == 0)
            continue;
        strcat(buf, pdirent->d_name);
        strcat(buf, " ");
    }
    train_t train;
    train.dataLength = strlen(buf);
    strcpy(train.buf, buf);
    send(netFd, &train, sizeof(train.dataLength) + train.dataLength, MSG_NOSIGNAL);
    return 0;
}

int pwd(char *pwd, int netFd){
    train_t train;
    strcpy(train.buf, pwd);
    train.dataLength = strlen(train.buf);
    send(netFd, &train, sizeof(train.dataLength) + train.dataLength, MSG_NOSIGNAL);
    return 0;
}

int makedir(char *argv,char *pwd,int netFd){
    //makedir file1
    char arr[100] = "";
    strcpy(arr, argv);
    char *word = strtok(arr," ");
    char *filePath = strtok(NULL," ");
    char realPath[200] = {0};
    sprintf(realPath, ".%s", filePath);
    printf("realPath = %s\n", realPath);
    int ret = mkdir(realPath,0666);
    if(ret == -1){
        send(netFd, "0", 1, MSG_NOSIGNAL);
    }else{
        send(netFd, "1", 1, MSG_NOSIGNAL);
        strcpy(pwd, filePath); 
    }
}
